package util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.google.common.collect.Maps.newHashMapWithExpectedSize;

/**
 * Created by Arat.Wu on 2017/12/06.
 *
 * 根据WeChat信dat的HEX获取加密key
 */
public class WechatDatKey {
    private final static Map<String, String> FILE_TYPE_MAP = newHashMapWithExpectedSize(3);

    public static String getDatKey(int Hex0,int Hex1,int Hex2,int Hex3){
        FILE_TYPE_MAP.put("jpg", "ffd8ffe000104a464946"); //JPEG (jpg)
        FILE_TYPE_MAP.put("png", "89504e470d0a1a0a0000"); //PNG (png)
        FILE_TYPE_MAP.put("gif", "47494638396126026f01"); //GIF (gif)

        String key="";
        String picType="";
        Set<String> set= FILE_TYPE_MAP.keySet();
        for(String s:set) {

            int hex0 = Integer.valueOf(FILE_TYPE_MAP.get(s).substring(0, 2),16);
            int hex1 = Integer.valueOf(FILE_TYPE_MAP.get(s).substring(2, 4),16);
            int hex2 = Integer.valueOf(FILE_TYPE_MAP.get(s).substring(4, 6),16);
            int hex3 = Integer.valueOf(FILE_TYPE_MAP.get(s).substring(6, 8),16);

            if((hex0^Hex0)==(hex1^Hex1)
                    &&(hex2^Hex2)==(hex3^Hex3)
                    &&(hex0^Hex0)==(hex3^Hex3)){

                key =Integer.toHexString(hex0^Hex0);
                picType = s;
            }
        }

        return "key:0x"+key+"\npicType:"+picType;
    }

    public static void main(String[] args){
        System.out.println(getDatKey(0x74,0x53,0x74,0x6b));
    }

}
